//
//  LocationViewController.m
//  ACE
//
//  Created by Mickey Yin on 2021/12/14.
//

#import "LocationViewController.h"
#import <CoreLocation/CoreLocation.h>//引入Corelocation框架

@interface LocationViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;//设置manager
@property (nonatomic, strong) NSString *currentCity;
@property (nonatomic, strong) UILabel *cityL;
@end

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    self.cityL = [[UILabel alloc] init];
    self.cityL.textColor = UIColor.grayColor;
    self.cityL.numberOfLines = 0;
    self.cityL.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.cityL];
    [self.cityL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(160);
    }];
    
    [self locate];
}

- (void)locate {
    if ([CLLocationManager locationServicesEnabled]) {//监测权限设置
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;//设置代理
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//设置精度
        self.locationManager.distanceFilter = 1000.0f;//距离过滤
        [self.locationManager requestAlwaysAuthorization];//位置权限申请
        [self.locationManager startUpdatingLocation];//开始定位
    }else {
        NSLog(@"no定位");
    }
}

#pragma mark location代理
- (void)aleartTips {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未开启定位服务，是否需要开启？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    UIAlertAction *queren = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *setingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]canOpenURL:setingsURL];
    }];
    [alert addAction:cancel];
    [alert addAction:queren];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    [self.locationManager stopUpdatingLocation];//停止定位
    
    //地理反编码
    CLLocation *currentLocation = [locations lastObject];
    
    CLLocationCoordinate2D coordinate = currentLocation.coordinate;
    NSLog(@"纬度:%f  经度:%f", coordinate.latitude, coordinate.longitude);
    
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当系统设置为其他语言时，可利用此方法获得中文地理名称
    NSMutableArray
    *userDefaultLanguages = [[NSUserDefaults standardUserDefaults]objectForKey:@"AppleLanguages"];
    // 强制 成 简体中文
    [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans", nil]forKey:@"AppleLanguages"];
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            NSString *city = placeMark.locality;
            if (!city) {
                self.currentCity = @"无法定位当前城市"; // @"⟳定位获取失败,点击重试1";
            } else {
                self.currentCity = placeMark.locality ;//获取当前城市
                
                self.currentCity = [NSString stringWithFormat:@"%@%@",placeMark.locality, placeMark.name];
                NSLog(@"erroe %@ -- %@ -- %@ -- %@ -- %@", placeMark.country, placeMark.administrativeArea, placeMark.locality, placeMark.thoroughfare, placeMark.name);
            }

        } else if (error == nil && placemarks.count == 0 ) {
            NSLog(@"erroe");
            self.currentCity = @"定位出错";
        } else if (error) {
            self.currentCity = error.localizedDescription; //@"⟳定位获取失败,点击重试3";
            NSLog(@"erroe %@", error.localizedDescription);
        }
        // 还原Device 的语言
        [[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //回到主线程，执行UI刷新操作
            self.cityL.text = [NSString stringWithFormat:@"%@\n%f  %f", self.currentCity, coordinate.latitude, coordinate.longitude];
        });
        
    }];
}

#pragma mark---------定位失败-----------
- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error {
    
    if([error code] ==kCLErrorDenied || [error code] ==kCLErrorRegionMonitoringDenied) { //访问被拒绝
        [self aleartTips];
        
    } else if ([error code] ==kCLErrorLocationUnknown) { //无法获取位置信息 目前位置是未知的,但CL将继续努力
        //ALERT(@"提示", @"无法获取位置信息");
        
    } else if ([error code] == kCLErrorNetwork) {
        //检查当前的网络状况
    }
}

@end
